﻿(function($) {
	$.fn.numkeyboard = function(options) {
		var defaults = {
			keyboardRadix: 1000, 
			animatetime: 300, 
			mainbackground: '#C8BFE7', 
			menubackground: '#4A81B0', 
			exitbackground: '#4376A0', 
			buttonbackground: '#ff730e', 
			clickeve: false 
		}
		var options = $.extend(defaults, options);
		var keyboardRadix = options.keyboardRadix;
		if(keyboardRadix < 300) {
			keyboardRadix = 300;
		}
		var numkeyboardcount = 0;
		var activeinputele;
		if($("#keyBoardPanel").length>0){
			$("#keyBoardPanel").remove();
		}
		this.each(function() {
			numkeyboardcount++;
			//添加唯一的数字键盘
			if(numkeyboardcount < 2) {
				$("body").append("<div id='keyBoardPanel' class='auth_keybord'>" +
					"<div id='auth_limit'></div>"+
					"<div id='inputdiv'><input type='number' class='auth_input'></input></div>"+
					"<div id='delectBtn'><img src='../../images/arrow.png' /></div>"+
					"<ul class='number_list' id='number_list'>" +
					"<li><button type='button'>7</button></li>" +
					"<li><button type='button'>8</button></li>" +
					"<li><button type='button'>9</button></li>" +
					"<li><button type='button'>4</button></li>" +
					"<li><button type='button'>5</button></li>" +
					"<li><button type='button'>6</button></li>" +
					"<li><button type='button'>1</button></li>" +
					"<li><button type='button'>2</button></li>" +
					"<li><button type='button'>3</button></li>" +
					"<li><button type='button'>0</button></li>" +
					"<li id='okBtnLi'><button type='button' id='okBtn'>确定</button></li>" +
					"</ul><div class='countDiv'>"+
					"<button type='button' style='margin: 15px 0px 0px 6px;'>100</button>"+
					"<button type='button' style='margin: 12px 0px 0px -17px;;'>600</button>"+
					"<button type='button' style='margin: 12px 0px 0px -17px;'>1000</button>"+
					"</div></div>");
			}
			//元素选择器
			var inputele = $(this);
			var keyboard = $("#keyBoardPanel");
			var keyboard_input = $(".auth_input");
			var keyboard_limit = $("#auth_limit");
			var keyboard_delectbtn = $("#delectBtn");
			var keyboard_exit = $("#auth_keybord_exit");
			var keyboard_menu = $("#auth_keybord_menu")
			var keyboard_inputdiv = $("#inputdiv");
			var keyboard_buttonul = keyboard.find('ul:first');
			var keyboard_buttonli = keyboard_buttonul.children('li');
			var keyboard_button = keyboard_buttonli.children('button');
			var keyboard_okBtnLi = $("#okBtnLi");
			var keyboard_okBtn = $("#okBtn");
			var keyboard_countDiv = $(".countDiv");
			var keyboard_countDivBtn = keyboard_countDiv.children('button');
			
			//第一次输入数字时，默认覆盖
			var changeBool = false;
			
			var buttonborder = '2px solid #31495a';
			//元素css样式控制
			keyboard.css({
				"position": "absolute",
				"z-index": "10",
				"display": "none",
				"background": options.mainbackground,
				overflow: "hidden",
				"width": keyboardRadix * 0.55,
				"height": keyboardRadix * 0.55,
				"border-radius": keyboardRadix * 0.01,
				"border":"6px solid #4f7d9d",
				"z-index":9999999,
				
			});
			keyboard_inputdiv.css({
				"float":"left"
			});
			keyboard_input.css({
				"margin-left": 26,
			    "background": "#000000",
			    "border": 0,
			    "height": 42,
			    "width": 138,
			    "margin-top": 15,
			    "margin-bottom": 12,
		        "border-radius": 3,
		        "color":"#ffffff",
		        "font-size":19.2
			});
			keyboard_delectbtn.css({
				padding: "0",
				"cursor": "pointer",
				"background": options.buttonbackground,
				"text-align": "center",
				"width": keyboardRadix * 0.11,
				"height": keyboardRadix * 0.07,
				"border-radius": keyboardRadix * 0.004,
				border: buttonborder,
				"line-height": keyboardRadix * 0.07 + "px",
				margin: "15px 0 0 " + keyboardRadix * 0.01 + "px",
				display: "inline-block",
				float:"left"
			});
			keyboard_limit.css({
				"margin-left":20,
				"margin-top":20,
				"color":"#ffffff"
			});
			keyboard_exit.css({
				"position": "absolute",
				"z-index": "1",
				"right": "0",
				"background": options.exitbackground,
				"cursor": "pointer",
				"text-align": "center",
				"width": keyboardRadix * 0.16,
				"height": keyboardRadix * 0.081,
				"border-top-right-radius": keyboardRadix * 0.01,
				"line-height": keyboardRadix * 0.081 + "px",
				"font-family": "'微软雅黑',arial",
				"font-size": keyboardRadix * 0.036 + "px",
				"corlor": "#000",
				"letter-spacing": keyboardRadix * 0.005
			});
			keyboard_menu.css({
				position: "relative",
				background: options.menubackground,
				cursor: "move",
				margin: "auto",
				width: keyboardRadix * 0.6,
				height: keyboardRadix * 0.081,
				"border-top-left-radius": keyboardRadix * 0.01,
				"border-top-right-radius": keyboardRadix * 0.01
			});
			keyboard_buttonul.css({ position: "relative", width: keyboardRadix * 0.4, height: keyboardRadix * 0.37 ,margin:"0 0 0 20px",padding:0,clear:"both",float:"left"});
			keyboard_buttonli.css({ position: "relative", margin: "auto", overflow: "hidden", "float": "left", width: keyboardRadix * 0.12, height: keyboardRadix * 0.09 });
			keyboard_button.css({
				"position": "relative",
				"float": "left",
				padding: "0",
				"cursor": "pointer",
				"background": options.buttonbackground,
				"text-align": "center",
				"width": keyboardRadix * 0.11,
				"height": keyboardRadix * 0.07,
				"border-radius": keyboardRadix * 0.004,
				border: buttonborder,
				"line-height": keyboardRadix * 0.07 + "px",
				margin: "0 0 0 " + keyboardRadix * 0.01 + "px",
				"font-family": "'微软雅黑',arial",
				"font-size": keyboardRadix * 0.032 + "px",
				"color": "#fff"
			});
			
			keyboard_countDivBtn.css({
				"position": "relative",
				padding: "0",
				"cursor": "pointer",
				"background": options.buttonbackground,
				"text-align": "center",
				"width": keyboardRadix * 0.11,
				"height": keyboardRadix * 0.07,
				"border-radius": keyboardRadix * 0.004,
				border: buttonborder,
				"line-height": keyboardRadix * 0.07 + "px",
				"font-family": "'微软雅黑',arial",
				"font-size": keyboardRadix * 0.032 + "px",
				"color": "#fff"
			});
			/**
			 * 确定按钮的样式
			 */
			keyboard_okBtnLi.css({
				width: keyboardRadix * 0.24
			});
			
			/**
			 * 确定按钮的样式
			 */
			keyboard_okBtn.css({
				width: keyboardRadix * 0.23,
				background:"#ffaa00",
				color:"#000000",
				"border-radius": keyboardRadix * 0.006,
			});
			/**
			 * 数字键盘的按键点击样式
			 */
			keyboard_button.mousedown(function() {
				if($(this).text()!="确定"){
					$(this).css({ background: "#666", top: "2px" });
				}
			}).mouseup(function() {
				if($(this).text()!="确定"){
					$(this).css({ background: options.buttonbackground, top: "0" });
				}
			});
			
			/**
			 * 数字键盘的按键点击样式
			 */
			keyboard_countDivBtn.mousedown(function() {
				$(this).css({ background: "#666", top: "2px" });
			}).mouseup(function() {
				$(this).css({ background: options.buttonbackground, top: "0" });
			});
			
			/**
			 * 删除按钮的点击样式
			 */
			keyboard_delectbtn.mousedown(function() {
				$(this).css({ background: "#666", top: "2px" });
			}).mouseup(function() {
				$(this).css({ background: options.buttonbackground, top: "0" });
			});
			
			/**
			 * 删除一个数字
			 */
			keyboard_delectbtn.unbind("click").click(function(e){
				backspace();
			});

			/**
			 * 退出软键盘
			 */
			keyboard_exit.click(function() {
				exit(options.clickeve);
			});
			
			/**
			 * 点击舞台隐藏软键盘
			 */
			$(document).click(function(e){
				if(keyboard.css("display") == "block"){
					if(!activeinputele.is(e.target) && activeinputele.has(e.target).length ===0){
						if(!keyboard.is(e.target) && keyboard.has(e.target).length ===0){
							activeinputele.val(activeinputele.attr("currentvalue"));
							exit(options.clickeve);
						}
					}
				}
			});
		
			/**
			 * 输入框有焦点时，弹出软键盘
			 */
			inputele.focus(function(event) {
				activeinputele = $(this);
				var p = GetScreenPosition(this);
				keyboard.css({ "display": "block", "left": p.x, "top": p.y + $(this).height() * 1.2 });
				initKeyboard();
				mouseDrag();
				touchDrag();
			});
			/**
			 * 点击输入框后，弹出软键盘
			 */
			if(options.clickeve) {
				inputele.click(function() {
					activeinputele = $(this);
					var p = GetScreenPosition(this);
					keyboard.css({ "display": "block", "left": p.x, "top": p.y + $(this).height() * 1.2 });
					initKeyboard();
					mouseDrag();
					touchDrag();
				});
			}
			
			/**
			 * 数字键盘的初始状态
			 */
			function initKeyboard(){
				changeBool = false;
				keyboard_inputdiv.find("input:first").val(activeinputele.val());
				keyboard_inputdiv.find("input:first").attr("autofocus","autofocus");
				keyboard_inputdiv.find("input:first").select();
				keyboard_limit.html("【"+activeinputele.attr("msg")+"】"+activeinputele.attr("min")+"-"+activeinputele.attr("max"));
				if(activeinputele.attr("condition")){
					var conditionArray = activeinputele.attr("condition").split(',');
					keyboard_countDivBtn[0].innerHTML=conditionArray[0];
					keyboard_countDivBtn[1].innerHTML=conditionArray[1];
					keyboard_countDivBtn[2].innerHTML=conditionArray[2];
					keyboard.css({
						"width": keyboardRadix * 0.55,
					});
				}else{
					keyboard.css({
						"width": keyboardRadix * 0.44,
					});
				}
			}
			/**
			 * 注册数字按钮的点击监听事件
			 */
			if(numkeyboardcount < 2) {
				for(var i = 0; i < keyboard_button.length; i++) {
					numbuttonclick(i);
				}
				for(var i = 0; i < keyboard_countDivBtn.length; i++) {
					countbuttonclick(i);
				}
			}

			/**
			 * 监听数字键盘
			 * @param {Object} buttonnum
			 */
			function numbuttonclick(buttonnum) {
				keyboard_buttonli.children('button:eq(' + buttonnum + ')').click(function(e) {
					var buttontext = keyboard_buttonli.children('button:eq(' + buttonnum + ')').text();
					if(buttontext == "确定"){
						var inputtext = keyboard_inputdiv.find("input:first").val();
						if(inputtext !=""){
							activeinputele.val(inputtext);
							var e1 = jQuery.Event('oninput');
							activeinputele.trigger(e1);
							exit(options.clickeve);
						}
					}else if(buttontext == "退格") {
						backspace();
					}else if(buttontext == "清除") {
						keyclear();
					}else{
						clickkey(buttontext);
					}
				})
			}
			
			/**
			 * 监听右侧的三个数字键
			 * @param {Object} buttonnum
			 */
			function countbuttonclick(buttonnum) {
				keyboard_countDiv.children('button:eq(' + buttonnum + ')').click(function(e) {
					var buttontext = keyboard_countDiv.children('button:eq(' + buttonnum + ')').text();
					retclickkey(buttontext);
					changeBool = true;
				})
			}
			
			/**
			 * 清空键
			 */
			function keyclear() {
				activeinputele.val("");
			}

			/**
			 * 删除一个数字
			 */
			function backspace() {
				var inputtext = activeinputele.val();
				if(inputtext.length > 0) {
					inputtext = inputtext.substring(0, inputtext.length - 1);
					activeinputele.val(inputtext);
					keyboard_inputdiv.find("input:first").val(inputtext);
				}
			}

			/**
			 * 点击数字键，num+当前显示的数字即为最后的显示数字
			 * @param {Object} num
			 */
			function clickkey(num) {
				var inputtext = activeinputele.val();
				if(!changeBool){
					inputtext = num;
					changeBool = true;
				}else{
					inputtext = inputtext + num;
				}
				if(Number(inputtext)<=activeinputele.attr("max")){
					activeinputele.val(inputtext);
					keyboard_inputdiv.find("input:first").val(inputtext);
				}
			}
			
			/**
			 * 点击右侧的三个数字键，num为要显示的数字
			 * @param {Object} num
			 */
			function retclickkey(num) {
				inputtext = num;
				activeinputele.val(inputtext);
				
				keyboard_inputdiv.find("input:first").val(inputtext);
			}

			/**
			 * 退出数字键盘
			 */
			function exit() {
				changeBool = false;
				keyboard.css({ "display": "none" });
			}

			/**
			 * 获取数字键盘要显示的位置
			 * @param {Object} object
			 */
			function GetScreenPosition(object) {
				var position = {};
				position.x = object.offsetLeft;
				position.y = object.offsetTop;
				while(object.offsetParent) {
					position.x = position.x + object.offsetParent.offsetLeft;
					position.y = position.y + object.offsetParent.offsetTop;
					//保证软键盘在（1024，,78）的举行内
					if(position.x+keyboard.width()>=1024){
						position.x = position.x-keyboard.width();
					}
					if(position.y + keyboard.height()>768){
						position.y = position.y-keyboard.height()-50;
					}
					if(object == document.getElementsByTagName("body")[0]) {
						break;
					} else {
						object = object.offsetParent;
					}
				}
				return position;
			}
			
			
			
			function mouseDrag() {
				var moveEle = keyboard;
				var eventEle = keyboard_limit;
				var stx = etx = curX = sty = ety = curY = 0;
				var MAction = false;
				var eleLeft = +moveEle.css("left").split('px')[0];
				var eleTop = +moveEle.css("top").split('px')[0];
				eventEle.mousedown(function(event){
					MAction = true;
					stx = event.pageX;	
					sty = event.pageY;
					eleLeft = +moveEle.css("left").split('px')[0];
					eleTop = +moveEle.css("top").split('px')[0];
					event.preventDefault();
				}).mousemove(function(event){			
				if(MAction){
					var curX = event.pageX-stx;
					var curY = event.pageY-sty;				
					moveEle.css({"left":eleLeft+curX,"top":eleTop+curY});
					event.preventDefault();
				}});
				$("body").mouseup(function(event){
					stx = etx = curX = sty = ety = curY = 0;
					MAction = false;
						
				});
			}
			
		   function touchDrag() {
				var moveEle = keyboard;
				var eventEle = keyboard_limit;
		        var stx = sty = etx = ety = curX = curY = 0;
				var TAction = false;
				var eleLeft = +moveEle.css("left").split('px')[0];
				var eleTop = +moveEle.css("top").split('px')[0];
				
		        eventEle.on("touchstart", function(event) { //touchstart
		            var event = event.originalEvent;
					TAction = true;
					curX = curY = 0;
		            // 元素当前位置
					eleLeft = +moveEle.css("left").split('px')[0];
					eleTop = +moveEle.css("top").split('px')[0];
		            // 手指位置
		            stx = event.touches[0].pageX;
		            sty = event.touches[0].pageY;
		        });
		        eventEle.on("touchmove", function(event) {
		            if(TAction){
					var event = event.originalEvent;
		            event.preventDefault();
		            curX = event.touches[0].pageX - stx;
		            curY = event.touches[0].pageY - sty;
					//alert(eleLeft+"-"+gundongX);
					moveEle.css({"left":eleLeft+curX,"top":eleTop+curY});
					}
					
		        });
		        eventEle.on("touchend", function(event) {
					stx = etx = curX = sty = ety = curY = 0;
					MAction = false;
					
				 });
		
		        function getT3d(elem, ename) {
		            var elem = elem[0];
		            var str1 = elem.style.webkitTransform;
		            if (str1 == "") return "0";
		            str1 = str1.replace("translate3d(", "");
		            str1 = str1.replace(")", "");
		            var carr = str1.split(",");
		
		            if (ename == "x") return carr[0];
		            else if (ename == "y") return carr[1];
		            else if (ename == "z") return carr[2];
		            else return "";
		        }
		    }
		});
	};
})(jQuery);